<script setup>
import MyHeader from '@/components/netshop/header.vue'
import MyFooter from '@/components/netshop/footer.vue'
import {useRoute} from 'vue-router'
import {ref, onMounted, reactive, computed} from 'vue'
import {
  GetAddressInfoMessageService,
  addAddressInfoService,
  editAddressInfoService,
  DeleteAddressInfoMessageService
} from '@/api/netshop/address.js'
import WxPayIcon from '@/assets/images/wx-pay-icon.svg';
import AliPayIcon from '@/assets/images/ali-pay-icon.svg';
import {
  addOrderInfoService
} from '@/api/netshop/order.js'
import {ElMessage} from "element-plus";
import {CodeToText, regionData} from "element-china-area-data";

const route = useRoute()
const tableData = ref([]);
const formtableRef = ref()
onMounted(() => {
  // 创建一个包含查询参数的对象
  if (localStorage.getItem('petdetailId' || 'shopdetailId')) {

    const queryData = {
      id: route.query.id,
      shop_name: route.query.name,
      quantity:ref(1),
      Totalquantity: route.query.Totalquantity,
      picture: route.query.img_url,
      price: route.query.price,
      totalprice: route.query.price,
      kind:route.query.kind,
    };
    console.log(tableData)
    // 将对象推送到 tableData 数组中
    tableData.value.push(queryData);
  }
  loadAddressData()
})
const num = ref(1)
const handleChange = (row) => {
  row.quantity = num;
  row.totalprice = row.price * num.value
}
const times = ref()
const handleSelectionChange = (val) => {
  times.value = val.length
}
// 计算总价格
const totalAmount = computed(() => {
  const rawTotal = tableData.value.reduce((sum, item) => sum + item.totalprice, 0);
  return parseFloat(rawTotal).toFixed(2)
});

// 删除
const deleteRow = (row) => {
  const index = tableData.value.indexOf(row);
  if (index !== -1) {
    tableData.value.splice(index, 1); // 移除找到的索引处的行
    localStorage.removeItem('petdetailId' || 'shopdetailId')
  }
  console.log(tableData.value)
};
// 根据状态禁止按钮点击
const disabled = () => {
  return !tableData.value || tableData.value.length === 0;
};
// 状态条
const active = ref(0)

// 下一步
const next = () => {
  console.log(tableData.value)
  if (active.value++ > 3) {
    active.value = 0
  }
}
// 上一步
const pre = () => {
  if (active.value++ < 4) {
    active.value = 0
  }
}
// 显示地址数据并对地址数据进行修改添加
const addressData = ref([]);
const addressEdit = ref([]);
const pcaOptions = regionData;
const addlock = ref(false)
const loading = ref(false)

const loadAddressData = async () => {
  const id = localStorage.getItem('custom_id')
  loading.value = true
  await GetAddressInfoMessageService(id)
      .then((res) => {
        // console.log(res)
        addressData.value = res.data.data
        // console.log(addressData.value)
        loading.value = false
      })
      .catch((err) => {
        console.log(err)
      })
  for (let i in addressData.value) {
    addressEdit.value[i] = false; //3.2 初始化布尔数组   false：查看状态（非编辑状态）
  }
};

const addAddress = () => {
  addlock.value = true
  addressData.value.push({}); //3.3 新增地址
  addressEdit.value[addressData.value.length - 1] = true;
};

const editAddress = (index) => {
  addlock.value = false
  addressEdit.value[index] = !addressEdit.value[index];
};

const saveAddress = async (index, value) => {
  addressEdit.value[index] = !addressEdit.value[index];
  loading.value = true
  console.log(value)
  value.basic_address = getCodeToText(value.adpca)
  if (addlock.value == true) {
    if (typeof value.is_default === 'undefined') {
      value.is_default = false;
    }
    const custom_id = localStorage.getItem('custom_id')
    await addAddressInfoService(value, custom_id)
        .then((res) => {
          console.log(res)
          loading.value = false
          loadAddressData()
        })
        .catch((err) => {
          console.log(err)
        })
  } else {
    console.log(value)
    const custom_id = localStorage.getItem('custom_id')
    await editAddressInfoService(value, custom_id)
        .then((res) => {
          console.log(res)
          loading.value = false
          loadAddressData()
        })
        .catch((err) => {
          console.log(err)
        })
  }
};
const deleteAddress = async (index, value) => {
  if (value.id == undefined) {
    addressData.value.splice(index, 1)
  } else {
    console.log(value.id)
    await DeleteAddressInfoMessageService(value.id)
        .then((res) => {
          console.log(res)
          loadAddressData()
        })
        .catch((err) => {
          console.log(err)
        })
  }
};

const handleAddressNode = (value) => {
  // value为数组
  addressData.value.adpca = value[2]; //三级级联地址，只需要把第三级存入数据库即可
};
// 将地址编码转变成字
const getCodeToText = (codeArray) => {
  console.log(codeArray.length)
  let area = {
    'province': '',
    'city': '',
    'region': ''
  };
  switch (codeArray.length) {
    case 1:
      area += CodeToText[codeArray[0]];
      break;
    case 2:
      area += CodeToText[codeArray[0]] + "/" + CodeToText[codeArray[1]];
      break;
    case 3:
      area.province = CodeToText[codeArray[0]]
      area.city = CodeToText[codeArray[1]]
      area.region = CodeToText[codeArray[2]];
      break;
    default:
      break;
  }
  return area
};
const changetest = (val) => {
  console.log(typeof (val));
  console.log(val);
};
// 将选中的地址和购物车详情归拢到这个数据里面
const orderData = ref({})
// 选中地址
const handleCurrentChange = (val) => {
  orderData.value = val
  console.log(val)
}
// 生成订单号
// 生成唯一订单号的函数
const generateOrderNumber = () => {
  const currentTime = new Date();
  const randomLetters = generateRandomLetters(4);

  // 格式：YYYYMMDDHHmmss + 4 个随机大写字母
  const orderNumber = `${currentTime.getFullYear()}${padZero(currentTime.getMonth() + 1)}${padZero(currentTime.getDate())}${padZero(currentTime.getHours())}${padZero(currentTime.getMinutes())}${padZero(currentTime.getSeconds())}${randomLetters}`;

  return orderNumber;
}

// 生成随机大写字母的函数
const generateRandomLetters = (length) => {
  const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += letters.charAt(Math.floor(Math.random() * letters.length));
  }
  return result;
}

// 在数字前面补零的函数
const padZero = (num) => {
  return num < 10 ? `0${num}` : num;
}
// 结算
const handleJiesuan = async () => {
  if (!orderData.value || Object.keys(orderData.value).length === 0) {
    ElMessage.error('请先选中地址再来结算')
  } else {
    const orderNumber = generateOrderNumber();
    const buy_status = '0'
    orderData.value = {...orderData.value, ...tableData.value[0], orderNumber, buy_status}
    console.log('订单value',orderData.value)
    await addOrderInfoService(orderData.value)
        .then((res) => {
          console.log(res)
          if (active.value++ > 3) {
            active.value = 0
          }
        })
        .catch((err) => {
          console.log(err)
        })
  }
}

</script>
<template>
  <div>
    <MyHeader/>
    <el-steps style="margin-top: 100px;width: 60%;margin-left: 370px;margin-bottom: -100px" :active="active"
              finish-status="success" align-center="true">
      <el-step title="订单明细"/>
      <el-step title="选择地址"/>
      <el-step title="订单结算"/>
    </el-steps>
    <div v-show="active===0">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>订单明细</span>
          </div>
        </template>
        <el-table
            ref="multipleTableRef"
            :data="tableData"
            style="width: 90%;margin: 5px auto"
            table-layout="fixed"
        >
          <el-table-column property="shop_name" width="400" label="商品名称" align="center">
            <template #default="scope">
              <div class="row-image">
                <el-image
                    :src='scope.row.picture'
                    style="width:60%;height: 60%"
                    :preview-src-list='[scope.row.picture]'
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :initial-index="1"
                    preview-teleported="true"
                    alt="">
                </el-image>
                <div style="font-size: 17px;margin-left: 5px">{{ scope.row.shop_name }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column property="kind" label="商品种类" align="center">
            <template #default="scope">
              <span style="font-weight: bold;font-size: 20px">{{ scope.row.kind }}</span>
            </template>
          </el-table-column>
          <el-table-column property="price" label="单价" align="center">
            <template #default="scope">
              <span style="font-weight: bold;font-size: 20px">￥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column property="quantity" label="数量" align="center" width="250">
            <template #default="scope">
              <el-input-number v-model="num" :min="1" :max="scope.row.Totalquantity" @change="handleChange(scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column property="totalprice" label="总金额" align="center">
            <template #default="scope">
              <span style="font-weight: bold;font-size: 20px">￥{{ scope.row.totalprice }}</span>
            </template>
          </el-table-column>
          >
          <el-table-column property="operate" label="操作" align="center">
            <template #default="scope">
              <el-button @click="deleteRow(scope.row)" type="danger">
                <el-icon>
                  <Delete/>
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <div class="footer-right">
            <el-button v-if="active < 4" @click="next" :disabled="disabled()" size="large" style="margin-left: 20px"
                       type="success">
              下一步
            </el-button>
            <span class="money">￥{{ totalAmount }}</span>
            <span style="font-size: 30px">合计：</span>
          </div>
        </template>
      </el-card>
    </div>
    <div v-show="active===1">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>选择地址</span>
            <el-button class="button" type="text" style="float: right;margin-right: 50px" @click="addAddress">新增
            </el-button>
          </div>
        </template>
        <div class="card-body">
          <el-table
              v-loading="loading"
              :data="addressData"
              style="width: 100%;"
              @current-change="handleCurrentChange"
              highlight-current-row
          >
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <el-table-column prop="name" label="收货人" width="100">
              <template #default="scope">
                <el-input v-model="scope.row.name" v-if="addressEdit[scope.$index]"></el-input>
                <span v-else>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="mobile" label="联系方式" width="140">
              <template #default="scope">
                <el-input v-model="scope.row.mobile" v-if="addressEdit[scope.$index]"></el-input>
                <span v-else>{{ scope.row.mobile }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="adpca" label="收货地址" width="240" align="center">
              <template #default="scope">
                <el-cascader
                    v-model="scope.row.adpca"
                    :options="pcaOptions"
                    :props="addressProps"
                    placeholder="请选择"
                    @change="handleAddressNode"
                    filterable
                    :disabled="!addressEdit[scope.$index]"
                ></el-cascader>
              </template>
            </el-table-column>
            <el-table-column prop="detail" label="详细地址" width="180">
              <template #default="scope">
                <el-input v-model="scope.row.detail" v-if="addressEdit[scope.$index]"></el-input>
                <span v-else>{{ scope.row.detail }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="is_default" label="默认地址" width="100">
              <template #default="scope">
                <div v-if="addressEdit[scope.$index]">
                  <el-checkbox
                      v-model="scope.row.is_default"
                      :true-label="true"
                      :false-label="false"
                      @change="changetest"
                  >
                    设为默认
                  </el-checkbox>
                </div>
                <div v-else>
                  <el-tag v-if="scope.row.is_default === true" type="success" size="mini">默认</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
              <template #default="scope">
                <el-button
                    size="small"
                    v-if="!addressEdit[scope.$index]"
                    @click="editAddress(scope.$index)"
                >
                  <el-icon>
                    <Setting/>
                  </el-icon>
                  编辑
                </el-button>
                <el-button
                    size="small"
                    v-else
                    @click="saveAddress(scope.$index, scope.row)"
                >保存
                </el-button>
                <el-popconfirm
                    confirmButtonText="好的"
                    cancelButtonText="不用了"
                    icon="el-icon-info"
                    title="确定删除该地址？"
                    @confirm="deleteAddress(scope.$index, scope.row)"
                >
                  <template #reference>
                    <el-button
                        size="small"
                    >
                      <el-icon>
                        <Delete/>
                      </el-icon>
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="footer-right">
          <el-button v-if="active < 4" @click="handleJiesuan" size="large" style="margin-left: 20px"
                     type="success">
            结算
          </el-button>
          <el-button v-if="active > 0" @click="pre" size="large" style="margin-left: 20px"
                     type="primary">
            上一步
          </el-button>
        </div>
      </el-card>
    </div>
    <div v-show="active===2">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>请选择支付方式</span>
          </div>
        </template>
        <div class="card-body">
          <div class="pay-content">
            <div class="title">订单提交成功</div>
            <div class="text">支付金额</div>
            <div class="price">
              <span class="num">{{ orderData.totalprice }}</span>
              <span>元</span>
            </div>
            <div class="pay-choose-view" style="">
              <div class="pay-choose-box flex-view">
                <div class="choose-box choose-box-active">
                  <img :src="WxPayIcon">
                  <span>微信支付</span>
                </div>
                <div class="choose-box">
                  <img :src="AliPayIcon">
                  <span>支付宝</span>
                </div>
              </div>
              <div class="tips">请选择任意一种支付方式</div>
              <button class="pay-btn pay-btn-active" @click="handlePay()">确认支付</button>
            </div>
            <div class="pay-qr-view" style="display: none;">
              <div class="loading-tip" style="">正在生成安全支付二维码</div>
              <div class="qr-box" style="display: none;">
                <div id="qrCode" class="qr">
                </div>
                <div class="tips">请打开微信扫一扫进行支付</div>
                <button class="pay-finish-btn">支付完成</button>
                <button class="back-pay-btn">选择其他支付方式</button>
              </div>
            </div>
          </div>
        </div>
        <div class="footer-right">
          <el-button v-if="active > 0" @click="pre" :disabled="disabled()" size="large" style="margin-left: 20px"
                     type="success">
            上一步
          </el-button>
        </div>
      </el-card>
    </div>
    <MyFooter></MyFooter>
  </div>
</template>

<style scoped>
.box-card {
  width: 80%;
  height: 100%;
  margin: 0 auto;
  margin-top: 120px;
  border-radius: 30px;
}

.card-body {
  margin-left: 150px;
}

.card-header span {
  font-size: 30px;
  font-family: '微软雅黑';
  font-weight: bold;
  margin-left: 20px;
}

.row-image {
  display: flex;
  align-items: flex-start;
}

.footer-left {
  display: flex;
  flex-direction: row;
  float: left;
  margin-left: 20px;
}

.footer-right {
  display: flex;
  flex-direction: row-reverse;
  margin-right: 40px;
}

.money {
  font-size: 30px;
  font-weight: bold;
}

/*支付页面*/
.flex-view {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

.pay-content {
  position: relative;
  margin: 120px auto 0;
  width: 500px;
  background: #fff;
  overflow: hidden;
}

.title {
  color: #152844;
  font-weight: 500;
  font-size: 24px;
  line-height: 22px;
  height: 22px;
  text-align: center;
  margin-bottom: 11px;
}


.text {
  height: 22px;
  line-height: 22px;
  font-size: 14px;
  text-align: center;
  color: #152844;
}

.time {
  color: #f62a2a;
}

.text {
  height: 22px;
  line-height: 22px;
  font-size: 14px;
  text-align: center;
  color: #152844;
}

.price {
  color: #ff8a00;
  font-weight: 500;
  font-size: 16px;
  height: 36px;
  line-height: 36px;
  text-align: center;
}

.num {
  font-size: 28px;
}

.pay-choose-view {
  margin-top: 24px;
}

.choose-box {
  width: 140px;
  height: 126px;
  border: 1px solid #cedce4;
  border-radius: 4px;
  text-align: center;
  cursor: pointer;
}

.pay-choose-box {
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
  max-width: 300px;
  margin: 0 auto;
}

img {
  height: 40px;
  margin: 24px auto 16px;
  display: block;
}

.tips {
  color: #6f6f6f;
  font-size: 14px;
  line-height: 22px;
  height: 22px;
  text-align: center;
  margin: 16px 0 24px;
}

.choose-box-active {
  border: 1px solid #4684e2;
}

.tips {
  color: #6f6f6f;
  font-size: 14px;
  line-height: 22px;
  height: 22px;
  text-align: center;
  margin: 16px 0 24px;
}

.pay-btn {
  cursor: pointer;
  background: #c3c9d5;
  border-radius: 32px;
  width: 104px;
  height: 32px;
  line-height: 32px;
  border: none;
  outline: none;
  font-size: 14px;
  color: #fff;
  text-align: center;
  display: block;
  margin: 0 auto;
}

.pay-btn-active {
  background: #4684e2;
}

</style>